<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
      <el-form :model="form" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
        <div style="display: inline-block;width: 400px;">
          <span style="color:red;line-height:2.1;padding-right: 5px">*</span>
          <el-form-item label="生产工单" prop="orderId" >
            <el-select v-model="form.orderId" style="width:300px"  clearable>
              <el-option  v-for="orderlist in ProductionOrderList" :key="orderlist.id" :value="orderlist.id" :label="orderlist.code">{{orderlist.code}}</el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-search"
            size="mini"
            @click="payTypeAdd"
            v-if="this.$route.query.id == null"
            style="width: 80px;height: 30px;margin-top: 10px"
            v-hasPermi="['system:CustomerSettleCheckSheet:query']"
          >查询</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <el-form ref="form" :model="form1" :rules="rules" label-width="80px" >
        <el-table :data="productionPickingItemList" height="300px" ref="myTable" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>

          <el-table-column label="仓库名称" prop="warehouseName" width="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.warehouseId" @keyup.enter.native="handleQuery" clearable>
                <el-option v-for="(type,index) in StoreCenterInfoList" :key="index" :value="type.id" :label="type.name">{{type.name}}</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料ID" prop="materialId" width="200"/>
          <el-table-column label="物料编码" prop="materialCode" width="200"/>
          <el-table-column label="物料名称" prop="materialName" width="200"/>
          <el-table-column label="实际数量" prop="actualQuantity" width="200"/>
          <el-table-column label="备注" prop="remark" width="300">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.remark" />
            </template>
          </el-table-column>
          <el-table-column>

          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div style="border: 1px gainsboro solid;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.remark" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm()">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listStoreCenterInfo,  } from "@/api/system/StoreCenterInfo";
import { listProductionOrder } from "@/api/system/ProductionOrder";
import { listProductionPicking, getProductionPicking, getProductionPickingList,delProductionPicking, addProductionPicking, updateProductionPicking } from "@/api/system/ProductionPicking";
import { listMaterialStock } from "@/api/system/MaterialStock";

import { parseTime } from '../../../utils/ruoyi'

function formatDateToBackend(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export default {
  name: "ProductionPickingAdd",
  data() {
    return {
      // 物料库存表格数据
      MaterialStockList: [],
      // 生产工单表格数据
      ProductionOrderList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      payIds: [],
      //选中的行
      selectedRows:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //状态颜色
      statusColor:"rgb(100, 100, 100)",
      // 总条数
      total: 0,
      // 应收款
      SettleInItem: [],
      //客户列表
      CustomerList:[],
      // 查询关于选中生产工单的详细信息
      productionPickingItemList: [],
      //用户列表
      UserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id: null,
        pickingNo: null,
        orderId: null,
        orderNo: null,
        pickingTime: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      form1: {
        warehouseId:null,
        materialId : null,
        materialCode:null,
        materialName:null,
        actualQuantity: null,
        remark:null
      },
      SettleFeeSheetAllList: [],
      //供应商费用
      SettleFeeSheet:[],
      SettleFeeSheet2:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100000,
        statusSh:3,
        status:0,
      },
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 100000
      },
      // 仓库表格数据
      StoreCenterInfoList: [],
    };
  },
  created() {
    //查询生产工单列表
    this.getList();
    //查询领料列表
    this.getListId();
    //查询仓库列表
    this.getStoreCenterInfo();
    //查询物料库存列表
    this.getMaterialStockList();
    this.loading = false;
  },
  methods: {
    parseTime,
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listProductionOrder(this.queryParams).then(response => {
        this.ProductionOrderList = response.rows;
        this.loading = false;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfo() {
      this.loading = true;
      listStoreCenterInfo({categoryType:2}).then(response => {
        this.StoreCenterInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物料库存列表 */
    getMaterialStockList() {
      this.loading = true;
      listMaterialStock(this.queryParams1).then(response => {
        this.MaterialStockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询领料列表 */
    getListId() {
      this.SettleFeeSheet=[];
      var list=[];
      listProductionPicking(this.queryParams1).then(response => {
        this.SettleFeeSheet2=response.rows;
        list=response.rows;
        for (var i=0;i<list.length;i++){
          this.SettleFeeSheet.push(list[i].id);
        }
      });
    },

    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pickingNo: null,
        orderId: null,
        orderNo: null,
        pickingTime: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.form1 = {
        warehouseId:null,
        materialId : null,
        materialCode:null,
        materialName:null,
        actualQuantity: null,
        remark:null
      };
      this.productionPickingItemList = [];
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.payIds = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },

    /** 提交按钮 */
    submitForm() {
      if (this.formInfo()) {
        if (this.form.id != null) {
          updateProductionPicking(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.SettleFeeSheet);
          const Code = getOrderCode(this.SettleFeeSheet2);
          this.form.id = newId;
          this.form.pickingNo = Code;
          this.form.productionPickingItemList=this.productionPickingItemList;
          for (var i = 0; i < this.productionPickingItemList.length; i++) {
            this.productionPickingItemList[i].pickingId = newId;
          }

          //获取生产工单编号
          for (var i = 0; i < this.ProductionOrderList.length; i++){
            if (this.ProductionOrderList[i].id == this.form.orderId) {
              this.form.orderNo=this.ProductionOrderList[i].code;
            }
          }
          addProductionPicking(this.form).then(response => {
            this.$modal.msgSuccess("领料成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },

    //提交表单验证
    formInfo() {
      //支付方式验证
      for (var j = 0; j < this.productionPickingItemList.length; j++) {
        if (this.productionPickingItemList[j].warehouseId == null || this.productionPickingItemList[j].warehouseId == '') {
          this.$modal.msgError("请选择第"+(j+1)+"行的仓库");
          return false;
        }
      }
      var list= this.MaterialStockList;

      for (var i=0;i<this.productionPickingItemList.length;i++){
        for (var j=0;j<list.length;j++){
          if (this.productionPickingItemList[i].warehouseId==list[j].warehouseId && this.productionPickingItemList[i].materialId==list[j].materialId){
            if (this.productionPickingItemList[i].actualQuantity>list[j].stockQuantity){
              this.$modal.msgError("第"+(i+1)+"行"+this.productionPickingItemList[i].materialName+"物料库存不足");
              return false;
            }
          }
          if (this.productionPickingItemList[i].warehouseId!=list[j].warehouseId && this.productionPickingItemList[i].materialId==list[j].materialId) {
            this.$modal.msgError("第" + (i + 1) + "行" + this.productionPickingItemList[i].materialName + "物料在仓库中不存在！");
            return false;
          }
        }
      }
      return true;
    },
    //添加时查询客户单据
    payTypeAdd() {

      if (this.form.orderId == null || this.form.orderId == "") {
        this.$modal.msgError("请选择生产工单！");
        return false;
      }
      //查询生产工单相关物料信息
      getProductionPickingList({
        id: this.form.orderId,
      }).then(response => {
        // 订单赋值
        this.productionPickingItemList = response.data;
      });
    },
  },
  //  路由离开
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.ct = true;
    next();
  }
};


// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="SCLL";  //生产领料
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].pickingNo.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].pickingNo.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
